<template>
    <div class="app-container slideform-mode">
        <div class="tool-container">
            <el-button class="tool-btn tool-btn-sub" type="primary" :disabled="disableDels" @click="$clickAuth('Del') && handleDeletes()">{{ $t('global.del') }}</el-button>
            <el-button class="tool-btn" type="primary" :disabled="!disableDels" @click="$clickAuth('Insert') && handleCreate()">{{ $t('global.insert') }}</el-button>
        </div>
        <div class="table-container">
            <div class="table-area">
                <el-table
                    :key="tableKey"
                    v-loading="listLoading"
                    height="calc(100vh - 250px)"
                    :data="list"
                    border
                    highlight-current-row
                    @selection-change="tableSelect"
                    @row-click="$clickAuth('Update') && handleRowClick($event)"
                >
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column :label="$t('role.roleName')" min-width="80px" align="center" prop="roleName" />
                    <el-table-column :label="$t('role.note')" min-width="80px" align="center" prop="roleRemark" />
                    <el-table-column :label="$t('role.creativeTime')" width="160px" align="center">
                        <template slot-scope="{row}">{{ parseTime(row.createdTime, '{y}-{m}-{d}') }}</template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
            </div>
            <div class="editform-area" :class="{'slide-form-show':slideFormVisible}">
                <div class="editform-bg">
                    <div class="editform-bg-tit">{{ $t('role.role') }}</div>
                    <img class="editform-bg-img" src="@/assets/imgs/bg/role.png" alt="">
                    <el-button class="editform-btn" type="primary" :disabled="!disableDels" @click="$clickAuth('Insert') && handleCreate()">{{ $t('global.insert') }}</el-button>
                </div>
                <transition name="fade-transform" mode="out-in">
                    <div v-show="slideFormVisible" class="slide-form-area">
                        <el-form ref="slideForm" class="slideForm-form" :rules="slideFormRules" :model="temp" label-position="top">
                            <el-form-item :label="$t('role.roleName')" prop="roleName">
                                <el-input v-model="temp.roleName" type="text" />
                            </el-form-item>
                            <el-form-item :label="$t('role.note')" prop="roleRemark">
                                <el-input v-model="temp.roleRemark" type="text" />
                            </el-form-item>
                            <el-form-item :label="$t('role.authorityList')" prop="roleAuthorityList">
                                <el-cascader
                                    :key="authSelectKey"
                                    v-model="temp.roleAuthorityList"
                                    :options="optionsAuth"
                                    :props="{multiple: true}"
                                    collapse-tags
                                />
                            </el-form-item>
                        </el-form>
                        <div class="slide-form-btn-box">
                            <el-button v-loading="submitLoading" class="slide-form-btn" type="primary" @click="slideFormSubmit">{{ $t('global.save') }}</el-button>
                        </div>
                    </div>
                </transition>
            </div>
        </div>
    </div>
</template>

<script>
import { asyncRoutes } from '@/router';
import { roleSearch, roleUpdate, roleInsert, roleDelete } from '@/api/admin/adminRole';
import { parseTime } from '@/utils';
import Pagination from '@/components/Pagination';
import { mapGetters } from 'vuex' // secondary package based on el-pagination

export default {
    name: 'TableSlideForm',
    components: { Pagination },
    data() {
        return {
            disableDels: true,
            tableKey: 0,
            list: null,
            total: 0,
            submitLoading: false,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 10
            },
            temp: {
                roleId: null,
                roleName: '',
                roleRemark: '',
                reserveda: '',
                roleAuthorityList: []
            },
            selectItems: [],
            slideFormVisible: false,
            authSelectKey: 0,
            optionsAuth: this.filterAsyncRoutes(asyncRoutes),
            authSelectArr: []
        };
    },
    computed: {
        ...mapGetters([
            'language'
        ]),
        slideFormRules() {
            return {
                roleName: [{ required: true, message: this.$t('role.roleNameTips'), trigger: 'blur' }],
                roleAuthorityList: [{ required: true, message: this.$t('role.authorityListTips'), trigger: 'change' }]
            }
        }
    },
    created() {
        this.getList();
        console.log(asyncRoutes);
        console.log(this.optionsAuth);
    },
    methods: {
        parseTime,
        getList() {
            this.listLoading = true;
            roleSearch(this.listQuery).then(response => {
                this.list = response.data;
                this.total = response.count;
                this.listLoading = false;
            });
        },
        // 递归所有路由
        filterAsyncRoutes(routes, father) {
            const _this = this
            const res = [];
            routes.forEach(route => {
                const tmp = { ...route };
                let opt = {};
                if (!tmp.hidden) {
                    if (tmp.children) {
                        if (tmp.meta) {
                            opt.value = '0';
                            opt.label = tmp.meta.title;
                            opt.children = this.filterAsyncRoutes(tmp.children, father ? father + '/' + tmp.path : tmp.path);
                        } else {
                            opt = this.filterAsyncRoutes(tmp.children, tmp.path)[0];
                        }
                    } else {
                        opt = {
                            value: father + '/' + tmp.path,
                            label: tmp.meta.title
                        };
                        if (tmp.name == 'ContactList') {
                            opt.children = [{
                                value: 'authorityUrl',
                                label: _this.$t('global.view')
                            }]
                        } else {
                            opt.children = [{
                                value: 'authorityUrl',
                                label: _this.$t('global.view')
                            }, {
                                value: 'authorityInsert',
                                label: _this.$t('global.insert')
                            }, {
                                value: 'authorityUpdate',
                                label: _this.$t('global.edit')
                            }, {
                                value: 'authorityDel',
                                label: _this.$t('global.del')
                            }]
                        }
                    }
                    res.push(opt);
                }
            });
            return res;
        },
        resetTemp() {
            this.temp = {
                roleId: null,
                roleName: '',
                roleRemark: '',
                reserveda: '',
                roleAuthorityList: []
            };
        },
        // 多选
        tableSelect(selection) {
            this.slideFormVisible = false;
            this.disableDels = selection.length <= 0;
            this.selectItems = selection.map((i) => {
                return i.roleId;
            });
            console.log(selection);
        },
        // 多选删除
        handleDeletes() {
            console.log(this.selectItems);
            this.$confirm(this.$t('extra.confirmDelete'), this.$t('global.hint'), {
                customClass: 'custom-msgbox',
                center: true
            }).then(() => {
                roleDelete(this.selectItems).then(res => {
                    this.getList(); // 刷新列表
                    this.$message({
                        type: 'success',
                        message: this.$t('tips.successDel')
                    });
                });
            });
        },
        // 行内点击
        handleRowClick(row, column, event) {
            ++this.authSelectKey;
            this.temp = Object.assign({}, row);
            this.temp.roleAuthorityList = JSON.parse(decodeURIComponent(this.temp.reserveda));
            this.slideFormVisible = true;
            this.$nextTick(() => {
                this.$refs['slideForm'].clearValidate();
            });
        },
        // 新增点击
        handleCreate() {
            ++this.authSelectKey;
            this.resetTemp();
            this.slideFormVisible = true;
            this.$nextTick(() => {
                this.$refs['slideForm'].clearValidate();
            });
        },
        // 新增|修改提交
        slideFormSubmit() {
            this.$refs['slideForm'].validate((valid, item) => {
                if (valid) {
                    const param = Object.assign({}, this.temp);
                    param.reserveda = encodeURIComponent(JSON.stringify(param.roleAuthorityList));
                    const authObj = {};
                    param.roleAuthorityList.forEach(item => {
                        const path = item[item.length - 2];
                        const auth = item[item.length - 1];
                        if (authObj[path]) {
                            authObj[path][auth] = 1;
                        } else {
                            authObj[path] = { [auth]: 1 };
                        }
                    });
                    const roleAuthorityList = [];
                    for (const key in authObj) {
                        if (authObj[key].authorityUrl) {
                            authObj[key].authorityUrl = key;
                            roleAuthorityList.push(authObj[key]);
                        }
                    }
                    param.roleAuthorityList = roleAuthorityList;
                    console.log(param);
                    this.submitLoading = true
                    if (param.roleId) {
                        // 修改
                        roleUpdate(param).then(res => {
                            this.getList(); // 刷新列表
                            this.slideFormVisible = false; // 关闭侧表单
                            this.$notify({
                                title: this.$t('global.success'),
                                message: this.$t('global.editSuccess'),
                                type: 'success'
                            });
                        }).finally(res => {
                            this.submitLoading = false
                        });
                    } else {
                        roleInsert(param).then(res => {
                            this.getList(); // 刷新列表
                            this.slideFormVisible = false; // 关闭侧表单
                            this.$notify({
                                message: this.$t('role.roleAddSuccess'),
                                type: 'success'
                            });
                        }).finally(res => {
                            this.submitLoading = false
                        });
                    }
                }
            });
        }
    }
};
</script>
